import 'package:flutter_architecture/src/features/cart/data/auth_repository.dart';
import 'package:flutter_architecture/src/features/cart/data/local_cart_repository.dart';
import 'package:flutter_architecture/src/features/cart/data/remote_cart_repository.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

import '../domain/cart.dart';

/// 方式一：
// class CartService {
//   final AuthRepository authRepository;
//   final LocalCartRepository localCartRepository;
//   final RemoteCartRepository remoteCartRepository;
//
//   CartService({
//     required this.authRepository,
//     required this.localCartRepository,
//     required this.remoteCartRepository,
//   });
// }
//
// final cartServiceProvider = Provider<CartService>((ref) {
//   return CartService(
//     authRepository: ref.watch(authRepositoryProvider),
//     localCartRepository: ref.watch(localCartRepositoryProvider),
//     remoteCartRepository: ref.watch(remoteCartRepositoryProvider),
//   );
// });

/// 方式二：
class CartService {
  final Ref ref;

  CartService(this.ref);

  // fetch the cart from the local or remote repository depending on the user auth state
  Future<Cart> _fetchCart() async {
    final user = ref.watch(authRepositoryProvider).currentUser;
    if (user == null) {
      return ref.watch(localCartRepositoryProvider).fetchCart();
    } else {
      return ref.watch(remoteCartRepositoryProvider).fetchCart(user.uid);
    }
  }

  // save the cart to the local or remote repository depending on the user auth state
  Future<void> _setCart(Cart cart) async {
    final user = ref.watch(authRepositoryProvider).currentUser;
    if (user == null) {
      return ref.watch(localCartRepositoryProvider).setCart(cart);
    } else {
      return ref.watch(remoteCartRepositoryProvider).setCart(user.uid, cart);
    }
  }

  // add an item to the local or remote cart depending on the user auth state
  Future<void> addItem(Item item) async {
    final cart = await _fetchCart();
    final updated = cart.addItem(item);
    await _setCart(updated);
  }

  // remove an item from the local or remote cart depending on the user auth state
  Future<void> removeItemById(String productId) async {
    final cart = await _fetchCart();
    final updated = cart.removeItemById(productId);
    await _setCart(updated);
  }

  // ets an item in the local or remote cart depending on the user auth state
  Future<void> setItem(Item item) async {
    final cart = await _fetchCart();
    final updated = cart.setItem(item);
    await _setCart(updated);
  }

  Future<void> updateItemIfExists(Item item) async {
    final cart = await _fetchCart();
    final updated = cart.items.containsKey(item.productId)
        ? cart.setItem(item)
        : cart.addItem(item);
    await _setCart(updated);
  }
}

final cartServiceProvider = Provider<CartService>((ref) {
  return CartService(ref);
});
